<?php

require_once 'Zend/Validate/Abstract.php';

class Core_Validate_UsernameExists extends Zend_Validate_Abstract
{
    const NOT_EXISTS = 'notUsernameExists';

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_EXISTS => "The given user name '%value%' doesn't exist in the database",
    );

    /**
     * usernames to be excluded from test
     *
     * @var string
     */
    protected $_exclude = array();

    /**
     * Sets validator options
     *
     * @param  array $options
     * @throws Core_Validate_Exception
     * @return void
     */
    public function __construct($options = array())
    {
        if (!is_array($options)) {
            /**
             * @see Core_Validate_Exception
             */
            require_once 'Core/Validate/Exception.php';
            throw new Core_Validate_Exception('The options of this validator have to be given as an array');
        } else {
            $options = array_unique($options);
            if (array_key_exists('exclude', $options)) {
                $this->setExclude($options['exclude']);
            }
        }
    }

    /**
     * Returns the exclude option
     *
     * @return string
     */
    public function getExclude()
    {
        return $this->_exclude;
    }

    /**
     * Sets the exclude option
     *
     * @param  array/string $name
     * @return Core_Validate_UsernameExists Provides a fluent interface
     */
    public function setExclude($name = null)
    {
        if (!is_array($name)) {
            $this->_exclude = array($name);
        } else {
            $this->_exclude = $name;
        }
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value does exist already as user name
     *
     * @param  string $value
     * @return boolean
     */
    public function isValid($value)
    {
        $value = (string)$value;
        $this->_setValue($value);

        $mdlUser = new Model_User();
        if ($mdlUser->userExists($value, $this->getExclude())) {
            return true;
        }
        $this->_error(self::NOT_EXISTS);
        return false;
    }
}